package com.simen.downloader;

import android.os.Handler;

import com.simen.downloader.util.AppLog;
import com.simen.downloader.util.FileStorageUtils;
import com.simen.downloader.util.Utils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by zhangming on 16/5/16.
 */
final class FileThread implements Runnable {

    private final String key;
    private final String logFilePath, filePath;
    private final DownloadEngine engine;

    public FileThread(DownloadEngine engine, String fileDir, String key) {
        this.engine = engine;
        this.key = key;
        this.logFilePath = FileStorageUtils.getDefaultLogFilePath(fileDir, key).getPath();
        this.filePath = FileStorageUtils.getDefaultFilePath(fileDir, key).getPath();
    }

    @Override
    public void run() {
        ReentrantLock lock = engine.getLockForUri(key);
        if (lock.isLocked()) {
            AppLog.dLog("the lock has been locked " + key);
        }

        lock.lock();
        try {
            //删除已下载的文件
            File file = new File(filePath), logfile = new File(logFilePath);
            if (Utils.fileExist(file)) {
                file.delete();
                AppLog.dLog("the file has been deleted " + filePath);
            }

            if (Utils.fileExist(logfile)) {
                logfile.delete();
                AppLog.dLog("the logfile has been deleted " + logFilePath);
            }

        } finally {
            lock.unlock();
            AppLog.dLog("the lock is unlocked " + key);
        }

    }
}
